
package com.zdkj.subway.stm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.dto.in.SwMessageDTO;
import com.zdkj.subway.stm.entity.*;
import com.zdkj.subway.stm.enums.InvoiceChechAuditTypeEnum;
import com.zdkj.subway.stm.enums.MessageEnums;
import com.zdkj.subway.stm.fegin.SubwayCheckService;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwParamLineMapper;
import com.zdkj.subway.stm.mapper.SwParamStationMapper;
import com.zdkj.subway.stm.mapper.SwStPettymoneyCheckMapper;
import com.zdkj.subway.stm.service.SwStPettymoneyCheckService;
import com.zdkj.subway.stm.util.LocalDateConverter;
import com.zdkj.subway.stm.util.LocalDateTimeConverter;
import com.zdkj.subway.stm.util.SerialNumberGenerator;
import com.zdkj.subway.stm.util.DateUtilStm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车站备用金盘点
 *
 * @author cxp
 * @date 2024-11-16 10:21:52
 */
@Service
@Slf4j
public class SwStPettymoneyCheckServiceImpl extends ServiceImpl<SwStPettymoneyCheckMapper, SwStPettymoneyCheck> implements SwStPettymoneyCheckService {

    @Autowired
    private SwParamLineMapper swParamLineMapper;

    @Autowired
    private SwParamStationMapper swParamStationMapper;

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private SupportService supportService;

    /**
     * 新增或修改车站备用金盘点
     * @param swStPettymoneyCheck
     * @return
     */
    @Override
    public boolean saveOrUpdatePettymoneyCheck(SwStPettymoneyCheck swStPettymoneyCheck) {
        PigxUser user = SecurityUtils.getUser();
        swStPettymoneyCheck.setLineCode(user.getLineCode());
        swStPettymoneyCheck.setStationCode(user.getStationCode());
        // 查询车站盘点日期的备用金盘点数据是否存在
        LambdaQueryWrapper<SwStPettymoneyCheck> newStationincome = Wrappers.<SwStPettymoneyCheck>lambdaQuery()
                .eq(SwStPettymoneyCheck::getLineCode, swStPettymoneyCheck.getLineCode())
                .eq(SwStPettymoneyCheck::getStationCode, swStPettymoneyCheck.getStationCode())
                .eq(SwStPettymoneyCheck::getDelFlag, "0")
                .eq(SwStPettymoneyCheck::getStatisticsDate, swStPettymoneyCheck.getStatisticsDate());
        SwStPettymoneyCheck stPettymoneyCheck = this.getOne(newStationincome);
        // 重新计算金额合计和差异
        calculateAmount(swStPettymoneyCheck);
        if (ObjectUtil.isNotEmpty(stPettymoneyCheck)) {
            // 修改备用金盘点
            swStPettymoneyCheck.setId(stPettymoneyCheck.getId());
            return this.updateById(swStPettymoneyCheck);
        }
        // 保存备用金盘点
        swStPettymoneyCheck.setCheckStatus("0");
        return this.save(swStPettymoneyCheck);
    }

    /**
     * 备用金盘点数据批量提交
     * @param ids
     * @param status
     * @return
     */
    @Override
    public boolean updateApprovalStatus(List<Integer> ids, String status, String auditType) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        List<SwStPettymoneyCheck> updateData = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        for (Integer id : ids) {
            SwStPettymoneyCheck stPettymoneyCheck = this.getById(id);
			/*
			SwStPettymoneyCheck stPettymoneyCheck = new SwStPettymoneyCheck();
            stPettymoneyCheck.setId(Long.valueOf(id));
			*/
            stPettymoneyCheck.setCheckStatus(status);

            //SwStPettymoneyCheck swStPettymoneyCheck = baseMapper.selectById(id);
            QueryWrapper<SwParamStation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CODE", stPettymoneyCheck.getStationCode());
            SwParamStation swParamStation = swParamStationMapper.selectOne(queryWrapper);

            // 格式化日期
            LocalDate statisticsDate = stPettymoneyCheck.getStatisticsDate();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
            String formattedDate = statisticsDate.format(formatter);

            SwMessageDTO swMessageDTO = new SwMessageDTO();
            swMessageDTO.setTitle(formattedDate+swParamStation.getName()+" 备用金盘点数据审核");
            swMessageDTO.setMsgType("审批");
            swMessageDTO.setCreatorName(user.getNikeName());
            swMessageDTO.setCreatorId(user.getId());


			UpdateWrapper<SwStPettymoneyCheck> updateWrapper=new UpdateWrapper<>();
            //盘点提交状态 0：未提交 1：已提交 2：车站驳回 3：车站审核通过 4.车间驳回 5.车间审核通过 6：部门驳回 7：部门审核通过
            if (status.equals("1")){
                swMessageDTO.setLineCode(stPettymoneyCheck.getLineCode());
                swMessageDTO.setStationCode(stPettymoneyCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车站提交，站长待审核");
				//后续审核人员置空
				stPettymoneyCheck.setAuditStationName("");
                stPettymoneyCheck.setAuditStationJobNo(""); 				
				stPettymoneyCheck.setAuditWorkshopName("");
                stPettymoneyCheck.setAuditWorkshopJobNo("");				
				stPettymoneyCheck.setAuditDeptName("");
                stPettymoneyCheck.setAuditDeptJobNo("");
				
				updateWrapper.set("AUDIT_STATION_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("2")){
                swMessageDTO.setLineCode(stPettymoneyCheck.getLineCode());
                swMessageDTO.setStationCode(stPettymoneyCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setContent("站长驳回");
				//后续审核人员置空
				stPettymoneyCheck.setAuditWorkshopName("");
                stPettymoneyCheck.setAuditWorkshopJobNo("");				
				stPettymoneyCheck.setAuditDeptName("");
                stPettymoneyCheck.setAuditDeptJobNo("");				

				//updateWrapper.set("AUDIT_STATION_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            }else if (status.equals("3")){
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());//站务车间
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("站长审核通过，车间票务专业待审核");
				
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("4")) {
                swMessageDTO.setLineCode(stPettymoneyCheck.getLineCode());
                swMessageDTO.setStationCode(stPettymoneyCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业驳回，站长待审核");
				//后续审核人员置空				
				stPettymoneyCheck.setAuditDeptName("");
                stPettymoneyCheck.setAuditDeptJobNo("");				
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("5")){
                swMessageDTO.setDeptId(MessageEnums.AUDIT_DEPT_ID.getCode());//安全技术室
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.PWGLJSRY_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业审核通过，部门票务专业待审核");
				
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("6")) {
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());//站务车间
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_PETTYMONEY_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("部门票务专业驳回，车间票务专业待审核");
            }

            log.info("备用金盘点数据审核==>id:{},status:{},auditType:{},nikeName:{},time:{},oldStatus:{}", id, status,auditType,user.getNikeName(),new Date(),stPettymoneyCheck.getCheckStatus());
            if (InvoiceChechAuditTypeEnum.AUDIT_STATION.getCode().equals(auditType)) { // 中心站长审核
                stPettymoneyCheck.setAuditStationName(user.getNikeName());
                stPettymoneyCheck.setAuditStationJobNo(user.getUserCode());
                stPettymoneyCheck.setAuditStationTime(LocalDateTime.now());
				//后续审核人员置空
				stPettymoneyCheck.setAuditWorkshopName("");
                stPettymoneyCheck.setAuditWorkshopJobNo("");
				
				stPettymoneyCheck.setAuditDeptName("");
                stPettymoneyCheck.setAuditDeptJobNo("");
				
            } else if(InvoiceChechAuditTypeEnum.AUDIT_WORKSHOP.getCode().equals(auditType)) { // 车间票务专业审核
                stPettymoneyCheck.setAuditWorkshopName(user.getNikeName());
                stPettymoneyCheck.setAuditWorkshopJobNo(user.getUserCode());
                stPettymoneyCheck.setAuditWorkshopTime(LocalDateTime.now());
				//后续审核人员置空
				stPettymoneyCheck.setAuditDeptName("");
                stPettymoneyCheck.setAuditDeptJobNo("");
				
            } else if(InvoiceChechAuditTypeEnum.AUDIT_DEPT.getCode().equals(auditType)) { // 部门票务专业审核
                stPettymoneyCheck.setAuditDeptName(user.getNikeName());
                stPettymoneyCheck.setAuditDeptJobNo(user.getUserCode());
                stPettymoneyCheck.setAuditDeptTime(LocalDateTime.now());
            }
			//updateData.add(stPettymoneyCheck);
			//UpdateWrapper<SwStPettymoneyCheck> updateWrapper=new UpdateWrapper<>();挪到上面
			
			updateWrapper.eq("id", id);
			
			this.update(stPettymoneyCheck, updateWrapper);
			log.info("备用金盘点数据审核=完成=>id");
            supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);
            
        }
		return true;
        //return updateBatchById(updateData);
    }

    /**
     * 车站导出备用金盘点表
     * @param id
     * @param response
     */
    @Override
    public void exportPettymoneyCheckForStation(Long id, HttpServletResponse response) {
        InputStream excelTemplate = null;
        if (ObjectUtil.isNotEmpty(id)) {
            SwStPettymoneyCheck pettymoneyCheck = this.getById(id);
            try {
                // 格式化日期
                LocalDate statisticsDate = pettymoneyCheck.getStatisticsDate();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
                String formattedDate = statisticsDate.format(formatter);
                // 查询车站名称
                JSONObject jsonObject = getlinenameOrStationName(pettymoneyCheck.getLineCode(), pettymoneyCheck.getStationCode());
                String stationName = jsonObject.getString("stationName");

                response.reset(); // 非常重要
				response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                final String fileName = URLEncoder.encode("车站备用金盘点表-"+stationName +"-" + formattedDate, "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

                excelTemplate = this.getClass().getResourceAsStream("/static/excel/template/SwStPettymoneyCheckExcelTemplate.xlsx");

                ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplate).build();
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();

                Map<String, Object> map = BeanUtil.beanToMap(pettymoneyCheck);

                map.put("statisticsDate", formattedDate);

                map.put("stationName", stationName);
                // 生成流水号
                SerialNumberGenerator serialNumber = new SerialNumberGenerator();
                map.put("serialNumber", serialNumber.generateSerialNumber());

                excelWriter.fill(map, writeSheet);
                excelWriter.finish();
            }  catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(excelTemplate != null){
                    try {
                        excelTemplate.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }

                }
            }
        }
    }

	  /**
     * 车站导出备用金盘点表 根据日期导出所有车站明细表
     * @param checkTime
     * @param response
     */
    @Override
    public void exportPettymoneyCheckForStationAll(String checkTime, HttpServletResponse response) {
	
        if (ObjectUtil.isNotEmpty(checkTime)) {
			 // 查询要导出的车站备用金盘点数据
			LambdaQueryWrapper<SwStPettymoneyCheck> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.apply("date_format(STATISTICS_DATE,'%Y-%m') = '" + checkTime+"'");
						
			queryWrapper.orderByDesc(SwStPettymoneyCheck::getStatisticsDate).orderByAsc(SwStPettymoneyCheck::getStationCode);
			List<SwStPettymoneyCheck> records = this.list(queryWrapper);
			
            InputStream excelTemplateIs = null;
            try {
				//获取已有的车站数据
				Map<String,SwStPettymoneyCheck> mapHaveData = new HashMap();
				String formattedDate = "";
               
				if(records!=null && records.size()>0){
					
				   SwStPettymoneyCheck data0 = records.get(0);
					// 格式化日期
                   LocalDate statisticsDate = data0.getStatisticsDate();
				  
                   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
                   formattedDate = statisticsDate.format(formatter);
				}
				records.forEach(item -> {
					// 查询车站名称
					JSONObject jsonObject = getlinenameOrStationName(item.getLineCode(), item.getStationCode());
					//设置盘点时间改为年月
					item.setStatisticsDateStr(DateUtilStm.localDateToString(item.getStatisticsDate(),"yyyy-MM"));
					item.setStationCode(jsonObject.getString("stationName"));
                   	mapHaveData.put(jsonObject.getString("stationName"),item); //key车站名字
			   });

			    response.reset(); // 非常重要
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                final String fileName = URLEncoder.encode("车站备用金盘点表(全部车站)-" + formattedDate, "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/SwStPettymoneyCheckAllStationExcelTemplate.xlsx");		                                                                           

                ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
			    
				List<Map<String,String>> stationMap = this.baseMapper.selectStationMap();        
               //车站循环,每个车站对应一个对象，为导出做准备
			   int i=0;//计数器，创建了多少个Sheet
			   for (Map<String,String> mapStations : stationMap) {
					String stationCode = mapStations.get("CODE");
					String stationName = mapStations.get("NAME");                     
					 i++;
					 SwStPettymoneyCheck entityExport = new SwStPettymoneyCheck();
					 boolean isExist = false;
					 if(mapHaveData!=null){
					    if(mapHaveData.containsKey(stationName)){
							isExist =true;
							entityExport = mapHaveData.get(stationName);                            
					    }
					}
					if(!isExist){
						entityExport.setStatisticsDateStr(formattedDate);					    
					}
					entityExport.setStationCode(stationName);
					
					Map<String, Object> map = BeanUtil.beanToMap(entityExport);
                    map.put("statisticsDate", formattedDate);
                    map.put("stationName", stationName);					
					WriteSheet writeSheet = EasyExcel.writerSheet(i-1,stationName).build();                   
                    excelWriter.fill(map,writeSheet);					
				 }

                excelWriter.finish();
            }  catch (Exception e) {
                e.printStackTrace();
				 log.error("车站备用金盘点表(全部车站)"+e.getMessage());
            } finally {
                if(excelTemplateIs != null){
                    try {
                        excelTemplateIs.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }

                }
            }
        }
    }

    /**
     * 审核页面导出备用金盘点表
     * @param swStPettymoneyCheck
     * @param response
     */
    @Override
    public void exportPettymoneyCheckForApproval(SwStPettymoneyCheck swStPettymoneyCheck, HttpServletResponse response) {
        // 导出日期范围
        List<String> statisticsDates = swStPettymoneyCheck.getDates1();
        // 导出车站集合
        List<String> stationCodes = swStPettymoneyCheck.getDates2();
        // 查询要导出的车站备用金盘点数据
        LambdaQueryWrapper<SwStPettymoneyCheck> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(statisticsDates)) {
//            queryWrapper.between(SwStPettymoneyCheck::getStatisticsDate, statisticsDates.get(0), statisticsDates.get(1));
            queryWrapper.apply("date_format(STATISTICS_DATE,'%Y-%m') between '" + statisticsDates.get(0) + "' and '" + statisticsDates.get(1) + "'");
        }
        if (ObjectUtil.isNotEmpty(stationCodes)) {
            queryWrapper.in(SwStPettymoneyCheck::getStationCode, stationCodes);
        }
        queryWrapper.orderByDesc(SwStPettymoneyCheck::getStatisticsDate).orderByAsc(SwStPettymoneyCheck::getStationCode);
        List<SwStPettymoneyCheck> records = this.list(queryWrapper);
        records.forEach(item -> {
            // 查询车站名称
            JSONObject jsonObject = getlinenameOrStationName(item.getLineCode(), item.getStationCode());
		    //设置盘点时间改为年月
			item.setStatisticsDateStr(DateUtilStm.localDateToString(item.getStatisticsDate(),"yyyy-MM"));
            item.setStationCode(jsonObject.getString("stationName"));
        });
        try {
            // 盘点提交状态字典转换
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.SW_ST_PETTYMONEY_CHECK_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            for (SwStPettymoneyCheck record : records) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                record.setCheckStatus(map.get(record.getCheckStatus()));
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("车站备用金盘点表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + statisticsDates.get(0) +"~"+ statisticsDates.get(1) + fileName +  DateUtilStm.getNowDayString("yyyy-MM-dd") + ".xlsx");
            // 设置内容样式
            WriteCellStyle writeCellStyle = new WriteCellStyle();
            writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            writeCellStyle.setBorderTop(BorderStyle.THIN);
            writeCellStyle.setBorderRight(BorderStyle.THIN);
            writeCellStyle.setBorderBottom(BorderStyle.THIN);
            writeCellStyle.setBorderLeft(BorderStyle.THIN);
            EasyExcel.write(response.getOutputStream(), SwStPettymoneyCheck.class).
                    sheet("盘点数据")
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                    .registerWriteHandler(new HorizontalCellStyleStrategy(new WriteCellStyle(), writeCellStyle))
                    .doWrite(records);
        } catch (IOException e) {
            log.error("导出车站备用金盘点数据失败");
        }
    }

    /**
     * 金额计算
     * @param swStPettymoneyCheck
     */
    private void calculateAmount(SwStPettymoneyCheck swStPettymoneyCheck) {
        // 100元金额
        BigDecimal hundredMoney = BigDecimal.valueOf(swStPettymoneyCheck.getHundredNumber() * 100);
        // 50元金额
        BigDecimal fiftiyMoney = BigDecimal.valueOf(swStPettymoneyCheck.getFiftiyNumber() * 50);
        // 20元金额
        BigDecimal twentyMoney = BigDecimal.valueOf(swStPettymoneyCheck.getTwentyNumber() * 20);
        // 10元金额
        BigDecimal tenMoney = BigDecimal.valueOf(swStPettymoneyCheck.getTenNumber() * 10);
        // 5元金额
        BigDecimal fiveMoney = BigDecimal.valueOf(swStPettymoneyCheck.getFiveNumber() * 5L);
        // 1元纸币金额
        BigDecimal onePaperMoney = BigDecimal.valueOf(swStPettymoneyCheck.getOnePaperNumber());
        // 1元硬币金额
        BigDecimal oneCoinMoney = BigDecimal.valueOf(swStPettymoneyCheck.getOneCoinNumber());
        // 5角纸币金额
        BigDecimal fivecentsPaperMoney = BigDecimal.valueOf(swStPettymoneyCheck.getFivecentsPaperNumber() * 0.5);
        // 5角硬币金额
        BigDecimal fivecentsCoinMoney = BigDecimal.valueOf(swStPettymoneyCheck.getFivecentsCoinNumber() * 0.5);
        // 2角纸币金额
        BigDecimal twocentsPaperMoney = BigDecimal.valueOf(swStPettymoneyCheck.getTwocentsPaperNumber() * 0.2);
        // 1角纸币金额
        BigDecimal onecentsPaperMoney = BigDecimal.valueOf(swStPettymoneyCheck.getOnecentsPaperNumber() * 0.1);
        // 1角硬币金额
        BigDecimal onecentsCoinMoney = BigDecimal.valueOf(swStPettymoneyCheck.getOnecentsCoinNumber() * 0.1);
        // 实际账面金额（100元金额 + 50元金额 + 20元金额 + 10元金额 + 5元金额 + 1元纸币金额 + 1元硬币金额 + 5角纸币金额 + 5角硬币金额 + 2角纸币金额 + 1角纸币金额 + 1角硬币金额）
        BigDecimal actualBookBalanceMoney = getBigDecimalSum(
                hundredMoney, fiftiyMoney, twentyMoney, tenMoney, fiveMoney, onePaperMoney, oneCoinMoney,
                fivecentsPaperMoney, fivecentsCoinMoney, twocentsPaperMoney, onecentsPaperMoney, onecentsCoinMoney
        );
        // 账面结余金额（手动填写）
        BigDecimal bookBalanceMoney = swStPettymoneyCheck.getBookBalanceMoney();
        // 计算差异金额（差异金额 = 实际账面金额 - 账面结余金额）
        BigDecimal diffBookBalanceMoney = actualBookBalanceMoney.subtract(bookBalanceMoney);
        // 设置备用金数据金额值
        swStPettymoneyCheck.setHundredMoney(hundredMoney);
        swStPettymoneyCheck.setFiftiyMoney(fiftiyMoney);
        swStPettymoneyCheck.setTwentyMoney(twentyMoney);
        swStPettymoneyCheck.setTenMoney(tenMoney);
        swStPettymoneyCheck.setFiveMoney(fiveMoney);
        swStPettymoneyCheck.setOnePaperMoney(onePaperMoney);
        swStPettymoneyCheck.setOneCoinMoney(oneCoinMoney);
        swStPettymoneyCheck.setFivecentsPaperMoney(fivecentsPaperMoney);
        swStPettymoneyCheck.setFivecentsCoinMoney(fivecentsCoinMoney);
        swStPettymoneyCheck.setTwocentsPaperMoney(twocentsPaperMoney);
        swStPettymoneyCheck.setOnecentsPaperMoney(onecentsPaperMoney);
        swStPettymoneyCheck.setOnecentsCoinMoney(onecentsCoinMoney);
        swStPettymoneyCheck.setActualBookBalanceMoney(actualBookBalanceMoney);
        swStPettymoneyCheck.setDiffBookBalanceMoney(diffBookBalanceMoney);
    }

    /**
     * 计算多个BigDecimal数相加和
     * @param i
     * @param arg
     * @return
     */
    public static BigDecimal getBigDecimalSum(BigDecimal i, BigDecimal... arg) {
        BigDecimal sum = i;
        for (BigDecimal b : arg) {
            sum = sum.add(b);
        }
        return sum;
    }

    /**
     * 获取线路名称&车站名称
     * @param lineCode
     * @param stationCode
     * @return
     */
    public JSONObject getlinenameOrStationName(String lineCode, String stationCode) {
        JSONObject object = new JSONObject();
        QueryWrapper<SwParamLine> queryWrapperLine = new QueryWrapper<>();
        queryWrapperLine.lambda().eq(SwParamLine::getCode, lineCode);
        List<SwParamLine> swParamLines = swParamLineMapper.selectList(queryWrapperLine);
        if (CollectionUtil.isNotEmpty(swParamLines)) {
            lineCode = swParamLines.get(0).getCode();
            object.put("lineName", swParamLines.get(0).getName());
            QueryWrapper<SwParamStation> queryWrapperStation = new QueryWrapper<>();
            queryWrapperStation.lambda().eq(SwParamStation::getLineCode, lineCode)
                    .eq(SwParamStation::getCode, stationCode);
            List<SwParamStation> swParamStations = swParamStationMapper.selectList(queryWrapperStation);
            if (CollectionUtil.isNotEmpty(swParamStations)) {
                object.put("stationName", swParamStations.get(0).getName());
            }
        }
        return object;
    }
}
